package com.cxh.mediasessiondemo;

import android.media.MediaMetadata;
import android.media.browse.MediaBrowser;
import android.media.session.MediaController;
import android.media.session.PlaybackState;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cxh.mediasessiondemo.adapter.CommonRVHolder;
import com.cxh.mediasessiondemo.adapter.CommonRvAdapter;

import java.util.List;
import java.util.Locale;

/**
 * Created by Cxh
 * Time : 2021/10/23  01:40
 * Desc :
 */
public class MusicUIManager implements View.OnClickListener, IMediaData {

    private MainClientActivity mActivity;
    private RecyclerView mRecyclerView;
    private TextView mTvTitle;
    private TextView mTvSubTitle;
    private SeekBar mSeekBar;
    private TextView mTvProcess;
    private Button mBtnPre;
    private Button mBtnPlay;
    private Button mBtnNext;
    private TextView mTvLoopState;

    private MusicRvAdapter mMusicAdapter;
    private MediaController mMediaController;

    public MusicUIManager(MainClientActivity activity) {
        mActivity = activity;
        mActivity.setContentView(R.layout.activity_main);

        mRecyclerView = mActivity.findViewById(R.id.rv_music_list);
        mTvTitle = mActivity.findViewById(R.id.tv_music_title);
        mTvSubTitle = mActivity.findViewById(R.id.tv_music_subtitle);
        mSeekBar = mActivity.findViewById(R.id.seek_bar);
        mTvProcess = mActivity.findViewById(R.id.tv_progress);
        mBtnPre = mActivity.findViewById(R.id.btn_pre);
        mBtnPlay = mActivity.findViewById(R.id.btn_play);
        mBtnNext = mActivity.findViewById(R.id.btn_next);
        mTvLoopState = mActivity.findViewById(R.id.tv_loop_state);

        mBtnPre.setOnClickListener(this);
        mBtnPlay.setOnClickListener(this);
        mBtnNext.setOnClickListener(this);
        mTvLoopState.setOnClickListener(this);
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                int max = seekBar.getMax();
                Bundle bundle = new Bundle();
                bundle.putInt(KEY_SEEKBAR_MAX, max);
                bundle.putInt(KEY_MEDIA_PROGRESS, progress);
                mMediaController.getTransportControls().sendCustomAction(ACTION_PROGRESS_CHANGE, bundle);
            }
        });

        mMusicAdapter = new MusicRvAdapter(mActivity);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mRecyclerView.setAdapter(mMusicAdapter);
        mMusicAdapter.setOnItemClickListener(new CommonRvAdapter.OnItemClickListener<MediaBrowser.MediaItem>() {
            @Override
            public void onItemClick(CommonRVHolder<MediaBrowser.MediaItem> holder, MediaBrowser.MediaItem data,
                                    int position) {
                if (null != mMediaController) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(KEY_AUTO_PLAY, true);
                    mMediaController.getTransportControls().prepareFromMediaId(data.getMediaId(), bundle);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_pre:
                mMediaController.getTransportControls().skipToPrevious();
                break;
            case R.id.btn_play: {
                if (BUTTON_TAG_PAUSE.equals(mBtnPlay.getTag())) {
                    mMediaController.getTransportControls().pause();
                } else if (BUTTON_TAG_PLAY.equals(mBtnPlay.getTag())) {
                    mMediaController.getTransportControls().play();
                }
            }
            break;
            case R.id.btn_next:
                mMediaController.getTransportControls().skipToNext();
                break;
            case R.id.tv_loop_state:
                mMediaController.getTransportControls().sendCustomAction(ACTION_LOOP_TYPE, null);
                break;
        }
    }

    public void setDataList(List<MediaBrowser.MediaItem> mediaItems) {
        mMusicAdapter.setList(mediaItems);

        if (null != mediaItems && mediaItems.size() > 0) {
            // 默认准备第一首
            MediaBrowser.MediaItem mediaItem = mediaItems.get(0);
            if (null != mMediaController) {
                mMediaController.getTransportControls().prepareFromMediaId(mediaItem.getMediaId(), null);
            }
        }
    }

    public void setMediaController(MediaController mediaController) {
        mMediaController = mediaController;
    }

    public void onPlaybackStateChanged(@Nullable PlaybackState state) {
        if (null == state) {
            return;
        }

        if (PlaybackState.STATE_PLAYING == state.getState()) {
            mBtnPlay.setText("暂停");
            mBtnPlay.setTag(BUTTON_TAG_PAUSE);
        } else {
            mBtnPlay.setText("播放");
            mBtnPlay.setTag(BUTTON_TAG_PLAY);
        }
    }

    public void onMetadataChanged(MediaMetadata mediaMetadata) {
        String title = mediaMetadata.getString(MediaMetadata.METADATA_KEY_TITLE);
        String subtitle = mediaMetadata.getString(MediaMetadata.METADATA_KEY_ARTIST);
        long duration = mediaMetadata.getLong(MediaMetadata.METADATA_KEY_DURATION);

        mTvTitle.setText(title);
        mTvSubTitle.setText(subtitle);
        mTvProcess.setText(String.format(Locale.CHINA, "%1$ds", duration / 1000));
    }

    public void onSessionEvent(String action, Bundle extras) {
        switch (action) {
            case ACTION_LOOP_TYPE: {
                if (null != extras) {
                    int loopType = extras.getInt(KEY_CURRENT_LOOP);
                    mTvLoopState.setText(getLoopText(loopType));
                }
            }
            break;
            case ACTION_HEARTBEAT: {
                if (null != extras) {
                    int progress = extras.getInt(KEY_MEDIA_PROGRESS);
                    int duration = extras.getInt(KEY_MEDIA_DURATION);
                    int index = extras.getInt(KEY_CURRENT_INDEX);
                    mSeekBar.setMax(duration);
                    mSeekBar.setProgress(progress);
                    mTvProcess.setText(String.format(Locale.CHINA, "%1$ds", (duration - progress) / 1000));
                    mMusicAdapter.setCurrentIndex(index);
                }
            }
            break;
        }
    }
}
